// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'boyi-5g77xpkp0aa0181c'
})

// 云函数入口函数
exports.main = async (event, context) => {

  // 获取微信上下文
  const wxContext = cloud.getWXContext()

  /** 检查参数是否传入 start */
  if (event._openId == undefined) {
    var result = {};
    result.errCode = 1;
    result.errMsg = "未传入必要参数";
    var data = {};
    result.data = data;
    return result;
  }
  console.log(event._openId)
  /** 检查参数是否传入 end */

  /** 推送消息 start */
  var today = new Date();
  var y = today.getFullYear();
  var m = today.getMonth() + 1;
  var d = today.getDate();
  var Today = y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
  try {
    const sendResult = await cloud.openapi.subscribeMessage.send({
      touser: event._openId,
      miniprogram_state: 'developer',
      page: 'pages/login/login',
      // 此处字段应修改为所申请模板所要求的字段
      data: {
        time3: {
          value: "" + Today,
        },
        thing1: {
          value: '请完成今日的健康打卡上报！！！',
        },
      },
      templateId: "G-k-iA2k_ttXzCuwsvXfJnElrU6ORdrwunWFxdaRlIg"
    })
    console.log(sendResult);
    var result = {};
    result.errCode = 0;
    result.errMsg = "操作成功";
    result.sendResult;
    var data = {};
    result.data = data;
    return result;
  } catch(err) {
    console.log();
    var result = {};
    result.errCode = 2;
    result.errMsg = err;
    var data = {};
    result.data = data;
    return result;
  }
  /** 推送消息 end */
}